<template>
	<section>
		<!--卡片视图-->
		<el-card>
			<!--添加角色按钮区域-->
			<el-row :span="24" class="toolbar" style="padding-bottom: 0px;">
				<el-col>
					<el-button type="primary" @click="addFormVisible=true">添加角色</el-button>
				</el-col>
			</el-row>

			<!--角色列表区域-->
			<el-table :data="roleListData" border stripe v-loading="listLoading">
				<!--展开列-->
				<el-table-column type="expand">
					<template slot-scope="scope">
						<el-column v-for="(item,i) in scope.row.permissions" :key="item.id">
								<el-tag closable @close="removePermissionById(scope.row,item.id)" type="warning">{{item.name}}</el-tag>
						</el-column>
					</template>
				</el-table-column>

				<!--索引列-->
				<el-table-column type="index" width="200px;"></el-table-column>
				<el-table-column label="角色名称" prop="name"></el-table-column>
				<el-table-column label="角色描述" prop="sn"></el-table-column>
				<el-table-column label="操作" >
					<template slot-scope="scope">
						<el-button type="primary" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
						<el-button type="danger" icon="el-icon-delete" @click="handleDel(scope.$index, scope.row)">删除</el-button>
						<el-button type="warning" icon="el-icon-setting" @click="showRolePermission(scope.row)">分配权限</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-card>

		<!--分配权限的对话框-->
		<el-dialog title="分配权限" :visible.sync="setRolePermissionVisible" width="50%">
			<!--展示数据的控件-->
			<el-tree :data="permissionList" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defKeys" ref="treeRef"></el-tree>
			<span slot="footer" class="dialog-footer">
   		 		<el-button @click="setRolePermissionVisible = false">取 消</el-button>
		 		<el-button type="primary" @click="allotPermission">确 定</el-button>
  			</span>
		</el-dialog>

		<!--新增界面-->
		<el-dialog title="新增角色" v-model="addFormVisible" :close-on-click-modal="false">
			<el-form :model="addForm" label-width="100px" :rules="addFormRules" ref="addForm">
				<el-form-item label="姓名" prop="name">
					<el-input v-model="addForm.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="标识" prop="sn">
					<el-input v-model="addForm.sn" auto-complete="off"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="addFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>

		<!--编辑界面-->
		<el-dialog title="编辑" v-model="editFormVisible" :close-on-click-modal="false">
			<el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
				<el-form-item label="姓名" prop="name">
					<el-input v-model="editForm.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="标识" prop="sn">
					<el-input v-model="editForm.sn" auto-complete="off"></el-input>
				</el-form-item>

			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
    export default {
        created() {
            this.getRoleListData()
        },
        data() {
            return {
                //所有角色列表数据
				roleListData:[],
				//控制分配权限对话框的显示与隐藏
                setRolePermissionVisible:false,
				//所有权限的数据
				permissionList:[],
				//树形控件的属性绑定
                treeProps:{
					label:'name',
					children:'child'
				},
				//默认选择的节点id值数组
                defKeys:[2,4],
				//当前选择分配角色的id
                roleId:'',
				//加载数据是，是否转圈圈
                listLoading:false,
				//新增界面是否显示
                addFormVisible: false,
                addLoading: false,
                addFormRules: {
                    name: [
                        { required: true, message: '请输入角色名称', trigger: 'blur' }
                    ],
                    sn: [
                        { required: true, message: '请输入角色说明', trigger: 'blur' }
                    ],
                },
                //新增界面数据
                addForm: {
                    name: '',
                    sn:''
                },

                editFormVisible: false,//编辑界面是否显示
                editLoading: false,
                editFormRules: {
                    name: [
                        { required: true, message: '请输入姓名', trigger: 'blur' }
                    ]
                },
                //编辑界面数据
                editForm: {
                    id: 0,
                    name: '',
                    sn:''
                }
            }
        },
        methods: {
            //查询所有角色
			async getRoleListData(){
                this.listLoading = true;
				const {data:res} = await this.$http.get('/role/all');

				if(!res.success){
				    return this.$message.error('获取角色列表失败');
				}

				this.roleListData=res.data;
                this.listLoading = false;

			},

			//根据id删除对应的权限
            async removePermissionById(role,permissionId){
				//弹框提示用户是否删除
                const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(err=>err)

				if(confirmResult !== 'confirm'){
                    return this.$message.info('取消删除')
				}

				const {data:res} = await this.$http.post('/permission/deleteRolePermission/'+role.id+'/'+permissionId,{})

				if (!res.success){
                    return this.$message.error('删除权限失败');
				}

				this.getRoleListData();
			},

			//展示分配权限的对话框
            async showRolePermission(row){
			    this.roleId=row.id
			    //获取所有权限的数据
                const {data:res} = await this.$http.get('/permission/findPermission');
                if(!res.success){
                    this.$message.error('获取权限失败');
				}

				//把获取到的权限数据保持到数据中
				this.permissionList=res.data;

                console.log(row.permissions)

				//每一次调用都得清空数组，不然会一直是第一次点击时的数据
				this.defKeys.length=0;

                this.getLeafKeys(row.permissions,this.defKeys);

                //弹出对话框
				this.setRolePermissionVisible=true;
			},

			//把当前角色已有的权限id存入到，默认选择的权限id数组中
			getLeafKeys(node,arr){
                for(let item of node){
                    arr.push(item.id);
				}
			},

			//点击为角色分配权限
            async allotPermission() {
                var ids = [
                    ...this.$refs.treeRef.getCheckedKeys()
                ]
                console.log(ids)

                let para = {
                    permission_ids: ids
                }
                const {data:res} = await this.$http.post('/permission/setRolePermission/' + this.roleId, para)

				if(res.success){
                    this.$message.success('分配权限成功')
                    this.setRolePermissionVisible=false;
                    this.listLoading = true;
                    this.getRoleListData();
				}else {
                    this.$message.error('分配权限失败')
				}
                this.listLoading = false;
            },

            //新增
			addSubmit() {
                this.$refs.addForm.validate((valid) => {
                     if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            this.addLoading = true;
                            //准备参数，将参数拷贝到para中
                            let para = Object.assign({}, this.addForm);
                            this.$http.post('/role/add',para).then(res => {
                                let ajaxResult = res.data;
                                this.addFormVisible = false;
                                if(!ajaxResult.success){
                                    this.$message.error('添加角色失败')
								}else {
                                    this.$message.success('添加成功');
								}
                                this.addLoading = false;
                                this.$refs['addForm'].resetFields();
								this.getRoleListData();

                            })
                        });
                    }
                });
            },

            //编辑
            editSubmit: function () {
                this.$refs.editForm.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            this.editLoading = true;
                            let para = Object.assign({}, this.editForm);
                            this.$http.post("/role/update",para).then(res =>{
                                let ajaxResult = res.data
                                if(!ajaxResult.success){
									this.$message.error('修改失败')
								}else{
                                    this.$message.success('修改成功');
								}
								this.$refs['editForm'].resetFields();
								this.editFormVisible = false;
								this.editLoading = false;
								this.getRoleListData();
                            })
                        });
                    }
                });
            },

            //显示编辑界面
            handleEdit: function (index, row) {
                this.editFormVisible = true;
                this.editForm = Object.assign({}, row);
            },

            //删除
            handleDel: function (index, row) {
                this.$confirm('确认删除该记录吗?', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.$http.delete('/role/delete/'+row.id,{}).then(res=>{
                        let ajaxResult =  res.data
                        if (!ajaxResult.success){
                           this.$message.error('删除失败')
                            this.getRoleListData();
                        }else {
                            this.$message.success('删除成功')
                            this.getRoleListData();
						}
                    })
                });
            }


			}


    }

</script>

<style scoped>
	.el-tag{
		margin: 7px;
	}
</style>